package com.wu.company.security;

import com.wu.company.domain.SysRole;
import com.wu.company.domain.SysUser;
import com.wu.company.entity.LoginUser;
import com.wu.company.entity.PrpDuser;
import com.wu.company.entity.Utiusergradetask;
import com.wu.company.service.PrpdUserRepository;
import com.wu.company.service.SysUserRepository;
import com.wu.company.service.UtiGradeTaskRepository;
import com.wu.company.service.UtiUserGradeTaskRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * created by wuyanshen on 2017/12/19 0:12
 */
@Component
public class WebUserDetailService implements UserDetailsService {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SysUserRepository sysUserRepository;

    @Autowired
    private PrpdUserRepository prpdUserRepository;
    @Autowired
    private UtiGradeTaskRepository utiGradeTaskRepository;

    @Autowired
    private MD5Util md5Util;
    @Autowired
    private Md5 md5;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("登录的用户名："+username);
        SysUser user = this.sysUserRepository.findByUsername(username);
//        PrpDuser user = this.prpdUserRepository.findByUserCode(username);
        if (user==null){
            logger.info("用户不存在！");
            throw new UsernameNotFoundException("用户名不存在");
        }
        logger.info("用户名:"+user.getUsername()+";密码:"+user.getPassword());
//        LoginUser loginUser = new LoginUser(username,user.getPassword(),true,true,true,true, getAuthorities(username),user);
        return user;
    }

    /**
     * 需要仔细研究一下这段代码
     * @return
     */
    public Collection<? extends GrantedAuthority> getAuthorities(String username) {
        List<String> task = utiGradeTaskRepository.findTaskCode("newPlatform%",username);
        List<SimpleGrantedAuthority> authorityCollection = new ArrayList<>();
        for(String userTask :task){
            authorityCollection.add(new SimpleGrantedAuthority(userTask));
        }

        return authorityCollection;
    }
}
